package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.PaiYiDaiUtil;
import com.block.datapush.service.apipush.utils.QiDaiAesUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.SecureRandom;

import org.apache.commons.codec.binary.Base64;

import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 89  拍易贷  回调
 */
@Service
public class PaiYiDaiPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        String mobileMd5 = memberSourceInfo.getMobileMd5();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("encryptMobile", mobileMd5);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex());
        bizMap.put("province", memberSourceInfo.getProvince());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("cnName", memberSourceInfo.getRealname());
        bizMap.put("system", 3);
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("amount", PaiYiDaiUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTime", PaiYiDaiUtil.getloantime(memberSourceInfo.getLoanTime()));
        bizMap.put("house", PaiYiDaiUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("vehicle", PaiYiDaiUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("shebao", PaiYiDaiUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("gongjijin", PaiYiDaiUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("insurance", PaiYiDaiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("zhima", PaiYiDaiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("licenseTime", 0);
        bizMap.put("education", PaiYiDaiUtil.getxueli(memberSourceInfo.getXueli()));
        bizMap.put("monthlyIncome", PaiYiDaiUtil.getShouRu(memberSourceInfo.getShouru()));
        bizMap.put("accountMoney", 0);
        bizMap.put("salaryPay", 0);
        bizMap.put("loanFor", PaiYiDaiUtil.getYongtu(memberSourceInfo.getYongtu()));
        bizMap.put("creditCard", 0);
        bizMap.put("job", PaiYiDaiUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("overdue", PaiYiDaiUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("weilidai", 0);
        bizMap.put("jdbaitiao", PaiYiDaiUtil.getjdbaitiao(memberSourceInfo.getBaitiao()));
        bizMap.put("huabei", PaiYiDaiUtil.gethuabei(memberSourceInfo.getHuabei()));

        String Key = getAesKey();
        String content = encrypt(JSON.toJSONString(bizMap), Key);

        String aesKey = PaiYiDaiUtil.encrypt(Key, pushApiKeyParam.getPubKey());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelCode", pushApiKeyParam.getApiCode());
        paramMap.put("content", content);
        paramMap.put("aesKey", aesKey);

        log.info("【拍易贷】撞库开始【queryUrl】{}【paramMap】{}【bizMap】{}", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【拍易贷】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String message = resultObject.getString("message");

        pushApiResult.setCode(code + "|" + message);
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0000")) {
            JSONObject data = resultObject.getJSONObject("data");
            String url = data.getString("url");
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("mobilePhone", memberSourceInfo.getMobile());
        bizMap.put("idNumber", memberSourceInfo.getReqIp());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex());
        bizMap.put("province", memberSourceInfo.getProvince());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("cnName", memberSourceInfo.getRealname());
        bizMap.put("system", 3);
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("amount", PaiYiDaiUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTime", PaiYiDaiUtil.getloantime(memberSourceInfo.getLoanTime()));
        bizMap.put("house", PaiYiDaiUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("gongjijin", PaiYiDaiUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("vehicle", PaiYiDaiUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("shebao", PaiYiDaiUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("insurance", PaiYiDaiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("zhima", PaiYiDaiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("licenseTime", 0);
        bizMap.put("education", PaiYiDaiUtil.getxueli(memberSourceInfo.getXueli()));
        bizMap.put("monthlyIncome", PaiYiDaiUtil.getShouRu(memberSourceInfo.getShouru()));
        bizMap.put("accountMoney", 0);
        bizMap.put("salaryPay", 0);
        bizMap.put("loanFor", PaiYiDaiUtil.getYongtu(memberSourceInfo.getYongtu()));
        bizMap.put("creditCard", 0);
        bizMap.put("job", PaiYiDaiUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("overdue", PaiYiDaiUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("weilidai", 0);
        bizMap.put("jdbaitiao", PaiYiDaiUtil.getjdbaitiao(memberSourceInfo.getBaitiao()));
        bizMap.put("huabei", PaiYiDaiUtil.gethuabei(memberSourceInfo.getHuabei()));

        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String jumpUrl = StrUtil.format("{}prodList", appInfoByAppCode.getH5Url(), memberSourceInfo.getChannelCode());
        bizMap.put("url", jumpUrl);

        String Key = getAesKey();
        String content = encrypt(JSON.toJSONString(bizMap), Key);

        String aesKey = PaiYiDaiUtil.encrypt(Key, pushApiKeyParam.getPubKey());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelCode", pushApiKeyParam.getApiCode());
        paramMap.put("content", content);
        paramMap.put("aesKey", aesKey);

        log.info("【拍易贷】导单开始【queryUrl】{}【paramMap】{}【bizMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【拍易贷】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String message = resultObject.getString("message");

        pushApiResult.setCode(code + "|" + message);
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0000")) {
            JSONObject data = resultObject.getJSONObject("data");
            String url = data.getString("url");
            String orderId = data.getString("orderId");

            pushApiResult.setOutOrderNo(orderId);
            pushApiResult.setApproveUrl(url);
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(false);
            pushApiResult.setStatus(PushStatusEnum.WAIT_QUERY.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());

        String requestUrl = pushApiKeyParam.getQueryUrl();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("orderId", pushQueryParam.getOutOrderNo());

        String Key = getAesKey();
        String content = encrypt(JSON.toJSONString(bizMap), Key);

        String aesKey = PaiYiDaiUtil.encrypt(Key, pushApiKeyParam.getPubKey());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelCode", pushApiKeyParam.getApiCode());
        paramMap.put("content", content);
        paramMap.put("aesKey", aesKey);

        log.info("【拍易贷】查询开始【requestUrl】{}【paramMap】{}【bizMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【拍易贷】查询结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String message = resultObject.getString("message");

        pushApiResult.setCode(code + "|" + message);
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0000")) {
            JSONObject data = resultObject.getJSONObject("data");
            Integer status = data.getInteger("status");
            if (StrUtil.equals(String.valueOf(status), "1")) {
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

    /**
     * 生成AES密钥，16位的强随机数
     */
    public static String getAesKey() {
        StringBuilder uid = new StringBuilder();
        Random rd = new SecureRandom();
        for (int i = 0; i < 16; i++) {
            int type = rd.nextInt(3);
            switch (type) {
                case 0:
                    //0-9的随机数
                    uid.append(rd.nextInt(10));
                    break;
                case 1:
                    //ASCII在65-90之间为大写, 获取大写随机
                    uid.append((char) (rd.nextInt(25) + 65));
                    break;
                case 2:
                    //ASCII在97-122之间为小写，获取小写随机
                    uid.append((char) (rd.nextInt(25) + 97));
                    break;
                default:
                    break;
            }
        }
        return uid.toString();
    }

    /**
     * AES加密
     *
     * @param contentStr 待加密的明文字符串
     * @return 密文数据
     */
    public static String encrypt(String contentStr, String key) {
        try {
            if (StringUtils.isEmpty(contentStr)) {
                return null;
            }
            byte[] raw = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(contentStr.getBytes(StandardCharsets.UTF_8));
            return new Base64().encodeToString(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
